package com.gm.wj.service;

import com.gm.wj.config.RedisConfig;
import com.gm.wj.dao.SysStudentDAO;
import com.gm.wj.entity.SysStudent;
import com.gm.wj.redis.RedisService;
import com.gm.wj.util.MyPage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.Set;

/**
 * @program: wj
 * @description: 学生
 * @author: Huang_shengjun
 * @create: 2020-09-16 22:23
 **/
@Slf4j
@Service
public class SysStudentService {


    @Autowired
    SysStudentDAO sysStudentDAO;
    @Autowired
    RedisService redisService;
    @Autowired
    UserService userService;
    @Autowired
    PermissionURL permissionURL;

    public MyPage list(int page, int size) {
        MyPage<SysStudent> students;
        // list缓存
        String key = "studentpage:" + page;
        Object studentPageCache = redisService.get(key);

        // 如果为空，就再查询一次，写入redis缓存
        if (studentPageCache == null) {
            Sort sort = Sort.by(Sort.Direction.DESC, "id");
            Page<SysStudent> studentInDb = sysStudentDAO.findAll(PageRequest.of(page, size, sort));
            students = new MyPage<>(studentInDb);
            // 设置redis过期时间  5s
            redisService.set(key, students, RedisConfig.DATA_REDIS_KEY_TIME);
        } else {
            students = (MyPage<SysStudent>) studentPageCache;
        }
        return students;
    }

//    public MyPage list(int page, int size) {
//        // 获取操作用户名
//        String username = (String) SecurityUtils.getSubject().getPrincipal();
//        MyPage<SysStudent> students;
//        // list缓存
//        String key = "studentpage:" + page;
//        Object studentPageCache = redisService.get(key);
//
//        // 如果为空，就再查询一次，写入redis缓存
//        if (studentPageCache == null) {
//            Sort sort = Sort.by(Sort.Direction.DESC, "id");
//            Pageable pageable = new PageRequest(page, size,sort);
//
//            // 重写 findAll方法  多条件查询
//            Page<SysStudent> studentInDb = sysStudentDAO.findAll((Specification<SysStudent>) (root, criteriaQuery, criteriaBuilder) -> {
//                List<Predicate> list = new ArrayList<Predicate>();
//                if(!permissionURL.isPermissionURL(SysStudent.class.getSimpleName(),username)){
//                    list.add(criteriaBuilder.equal(root.get("username").as(String.class), "%" + username + "%" ));
//                }
//                if(!"".equals(sysStudentQuery.isEnabled())){
//                    list.add(criteriaBuilder.like(root.get("enabled").as(String.class), "%" + sysStudentQuery.isEnabled() + "%"));
//                }
//                if(null!=sysStudentQuery.getStuNo()&&!"".equals(sysStudentQuery.getStuNo())){
//                    list.add(criteriaBuilder.equal(root.get("stuNo").as(String.class), "%" + sysStudentQuery.getStuNo() + "%"));
//                }
//                Predicate[] p = new Predicate[list.size()];
//                return criteriaBuilder.and(list.toArray(p));
//            },pageable);
//
//
//            students = new MyPage<>(studentInDb);
//            // 设置redis过期时间  5s
//            redisService.set(key, students,5);
//        } else {
//            students = (MyPage<SysStudent>) studentPageCache;
//        }
//        return students;
//    }

    public SysStudent findById(int id) {
        SysStudent sysStudent;
        String key = "student:" + id;
        Object studentCache = redisService.get(key);

        if (studentCache == null) {
            sysStudent = sysStudentDAO.findById(id);
            redisService.set(key, sysStudent,RedisConfig.DATA_REDIS_KEY_TIME);
        } else {
            sysStudent = (SysStudent) studentCache;
        }
        return sysStudent;
    }

    public int UseraddStu(SysStudent sysStudent) {
        sysStudentDAO.save(sysStudent);
        return 1;
    }

    @Transactional
    public int addOrUpdate(SysStudent sysStudent) {
        sysStudentDAO.save(sysStudent);
        redisService.delete("student" + sysStudent.getId());
        Set<String> keys = redisService.getKeysByPattern("studentpage*");
        redisService.delete(keys);

        int statu = userService.registerStu(sysStudent);
        if (statu != 1) {
            log.info("--进入回滚--" );
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }
       return 1;
    }

    public void delete(int id) {
        sysStudentDAO.deleteById(id);

        redisService.delete("student:" + id);
        Set<String> keys = redisService.getKeysByPattern("studentpage*");
        redisService.delete(keys);
    }

    public void updateStatus(SysStudent sysStudent) {
        SysStudent studentInDB = sysStudentDAO.findById(sysStudent.getId());
        studentInDB.setEnabled(sysStudent.isEnabled());
        sysStudentDAO.save(studentInDB);
    }


    public List<SysStudent> listByQueryKey(String queryKey1, String queryKey2, String queryKey3) {

        // 多条件模糊查询
//        queryKey1 = (queryKey1 == null && queryKey1 == "" ) ? null : "" + queryKey1 + ""; // booble值  直接用等于  不用like了
        queryKey1 = (queryKey1 == null) ? null : "%" + queryKey1 + "%";
        queryKey2 = (queryKey2 == null) ? null : "%" + queryKey2 + "%";
        queryKey3 = (queryKey3 == null) ? null : "%" + queryKey3 + "%";
        List<SysStudent> sysStudents = sysStudentDAO.find(queryKey1, queryKey2, queryKey3);

        return sysStudents;
    }

    public int findStudentData() {
        return sysStudentDAO.countByStudent();
    }

    public SysStudent findByUsername(String username) {
        return sysStudentDAO.findByUsername(username);
    }

    public SysStudent update(SysStudent sysStudent) {
        return sysStudentDAO.save(sysStudent);
    }
}
